package cn.com.anypay.manager.service;

import cn.com.anypay.manager.service.auth.factory.AuthStrategyFactory;
import cn.com.anypay.manager.service.auth.model.AuthRequest;
import cn.com.anypay.manager.service.auth.model.AuthResult;
import cn.com.anypay.manager.service.auth.strategy.IAuthStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 认证服务
 * 统一的认证入口，负责协调各种认证策略
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthService {

    private final AuthStrategyFactory authStrategyFactory;

    /**
     * 执行认证
     *
     * @param request 认证请求
     * @param servletRequest HTTP请求
     * @return 认证结果
     */
    public AuthResult authenticate(AuthRequest request, HttpServletRequest servletRequest) {
        log.info("开始执行认证: authType={}, identifier={}",
            request.getAuthType(), request.getIdentifier());

        try {
            // 获取对应的认证策略
            IAuthStrategy strategy = authStrategyFactory.getStrategy(request.getAuthType());

            // 执行认证
            AuthResult result = strategy.authenticate(request, servletRequest);

            if (result.isSuccess()) {
                log.info("认证成功: authType={}, identifier={}, userId={}",
                    request.getAuthType(), request.getIdentifier(),
                    result.getUser() != null ? result.getUser().getId() : null);
            } else {
                log.warn("认证失败: authType={}, identifier={}, error={}",
                    request.getAuthType(), request.getIdentifier(), result.getErrorMessage());
            }

            return result;

        } catch (Exception e) {
            log.error("认证过程发生异常: authType={}, identifier={}",
                request.getAuthType(), request.getIdentifier(), e);
            return AuthResult.failure("认证失败，请稍后重试");
        }
    }

    /**
     * 发送验证码
     *
     * @param authType 认证类型
     * @param identifier 标识符（手机号/邮箱等）
     */
    public void sendVerificationCode(String authType, String identifier) {
        log.info("发送验证码请求: authType={}, identifier={}", authType, identifier);

        try {
            // 获取对应的认证策略
            IAuthStrategy strategy = authStrategyFactory.getStrategy(authType);

            // 发送验证码
            strategy.sendVerificationCode(identifier);

            log.info("验证码发送成功: authType={}, identifier={}", authType, identifier);

        } catch (UnsupportedOperationException e) {
            log.warn("认证类型{}不支持发送验证码: identifier={}", authType, identifier);
            throw e;
        } catch (Exception e) {
            log.error("发送验证码失败: authType={}, identifier={}", authType, identifier, e);
            throw new RuntimeException("发送验证码失败，请稍后重试", e);
        }
    }

    /**
     * 检查认证类型是否支持
     *
     * @param authType 认证类型
     * @return true-支持，false-不支持
     */
    public boolean isAuthTypeSupported(String authType) {
        return authStrategyFactory.isSupported(authType);
    }

    /**
     * 获取所有支持的认证类型
     *
     * @return 支持的认证类型集合
     */
    public java.util.Set<String> getSupportedAuthTypes() {
        return authStrategyFactory.getSupportedAuthTypes();
    }
}